package com.jz.netthings.engine.init;

import com.jz.netthings.appengine.mapper.JzMachineMapper;
import com.jz.netthings.appengine.mapper.LocationMapper;
import com.jz.netthings.appengine.queue.ChairMgr;
import com.jz.netthings.appengine.queue.MachineMgr;
import com.jz.netthings.appengine.queue.ProviderQueue;
import com.jz.netthings.utils.AdscmDateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;

/**
 * 初始化缓存
 */
@Component
public class CacheInitApp {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    JzMachineMapper jzMachineMapper;
    @Autowired
    LocationMapper locationMapper;
    @Autowired
    ProviderQueue providerQueue;

    @Autowired
    RedisTemplate<Object , Object> objectRedisTemplate;

    @PostConstruct
    private void initMachineMgr(){
        logger.info("初始化采浆机器缓存...");

        //判断启动时间，如果系统时间在当天23:00 到第二天 5:00 前，那么都将缓存清理干净

        Date now = new Date();
        long currentTime = now.getTime();
        String dateFormat = AdscmDateUtils.getDateFormat(now);

        String endStr = dateFormat + " 23:00:00";
        String beginStr = dateFormat + " 05:00:00";

        long endTime = AdscmDateUtils.parseDateL(endStr).getTime();
        long beginTime = AdscmDateUtils.parseDateL(beginStr).getTime();

        if (currentTime > endTime || currentTime < beginTime){
            logger.info("当前系统时间在 23:00 - 5:00 之间，清理并初始化缓存...");
            MachineMgr.getInstance().reInitMachine(jzMachineMapper,objectRedisTemplate);
            providerQueue.cleanAll();
        }else {
            MachineMgr.getInstance().initialMachine(jzMachineMapper,objectRedisTemplate);

        }
        ChairMgr.getInstance().initChair(locationMapper);

    }

}
